#!/usr/bin/python
# coding=UTF-8
# noinspection PySingleQuotedDocstring
import requests
import json
import os
config = os.path.isfile("cookie.ini")
if config == True:
    print("正在启动...")
    os.system("cls")
else:
    print("请打开哔哩哔哩主页后按F12选择Network然后选下面的XHR，刷新网页，随意点击一项复制右侧出现的数据中cookie:后面的数据并粘贴进来")
    cookie = input()
    cf = open("cookie.ini","w",encoding="utf-8")
    print(cookie,file=cf)
    cf.close()
headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8",
    "cache-control": "no-cache",
    "cookie": cookie,
    "dnt": "1",
    "pragma": "no-cache",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36"
}
print("请输入需获取动态数据的用户UID")
uid = input()
url = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?host_uid="+str(uid)+"&offset_dynamic_id="
offset = "0"
usrurl = "http://api.bilibili.com/x/space/acc/info?mid="+str(uid)
usr = requests.get(url=usrurl,headers=headers)
usrobj = json.loads(usr.text)
name = usrobj["data"]["name"]
fp = open(name+".txt","w",encoding="utf-8")
fp.close()
while True:
    blurl = url+str(offset)
    back = requests.get(url=blurl,headers=headers)
    jstext = back.text
    jsonobj = json.loads(jstext)
    f = open(name+".txt","a",encoding="utf-8")
    print(back.content.decode("utf-8"),file=f)
    f.close()
    offset = jsonobj['data']['next_offset']
    if offset == 0:
        print("爬取结束")
        os.system("pause")
        break